<?php

        ////////////////////////////////////////////////////////////////////////
    //// CORE 
    //// MODEL CLASS
    //// INSERT UPDATE DELETE
    ////////////////////////////////////////////////////////////////////////    

        
        ( defined('BASEPATH') ) or exit('No direct access script allow !');
        
        
        class MY_Controller extends CI_Controller
        {
            var $data;
            
            var $page_limit;
			
			var $debug;
            
            public function __construct() 
            {
                parent::__construct();   

                // Check login
                if( !$this->session->userdata('logged_in') )
                {
                    $this->checkLogin();                            
                }                    
                
                $this->initAdminData(); 
                
                // page instance
                $this->page_limit = 10;
            }
            
            // Check login
            function checkLogin()
            {
                if( $this->session->userdata('logged_in') )
                {
                    $session_data = $this->session->userdata('logged_in');
                    $data['username'] = $session_data['username'];
                    redirect('admin/index');
                }
                else
                {
                    redirect('login','refresh');
                }
            }
            
            
            function initAdminData()
            {
                $this->data = array(
                  'title'           =>  'NDH Admin',                     
                  'company_info_links'   =>  array(
                        // Content links
                        array('link' => 'admin/news', 'title' => 'Quản lý nội dung', 'sub_menu' => array(
                                array('link' => 'admin/news/economic', 'title' => 'Kinh tế vĩ mô'),
                                array('link' => 'admin/news/expert', 'title' => 'Nhận định chuyên gia'),
                                array('link' => 'admin/news/report', 'title' => 'Báo cáo phân tích'),
                                array('link' => 'admin/news/market', 'title' => 'Nhận định thị trường'),                                                                    
                            )),
                        // Company info links
                        array('link' => 'admin/index', 'title' => 'Thông tin công ty', 'sub_menu' => array(
                                //array('link' => 'admin/finance', 'title' => 'Thông tin tài chính'),
                                array('link' => 'admin/index', 'title' => 'Thông tin cơ bản'),
                                //array('link' => 'admin/board', 'title' => 'Ban lãnh đạo và sở hữu'),
                                //array('link' => 'admin/analyze/basic', 'title' => 'Phân tích cơ bản'),
                                //array('link' => 'admin/analyze/technical', 'title' => 'Phân tích kỹ thuật'),                                        
                            )),
                        // Invest links
                        array('link' => 'admin/invest', 'title' => 'Danh mục đầu tư', 'sub_menu' => array(
                                /*array('link' => 'admin/investor', 'title' => 'Nhà đầu tư'),
                                array('link' => 'admin/invest/items', 'title' => 'Danh mục đầu tư'),                                                                */
                            )),
                       // Invest links
                        array('link' => 'admin/positions', 'title' => 'Chức vụ', 'sub_menu' => array(                                                                                               
                            )),                             
                    ),                    
                );
            }

            /*
            * Upload data use POST method
            * If post data is empty
            * then use existed data in database 
            */
            function uploadDataV1($file_name = false, $file_data = false)
            {
                $file_value = $this->input->post($file_name);
                if( empty($file_value) )
                {
                    $file_value = $file_data[$file_name];  
                }                                
                return $file_value;
            }

            /*
            * Upload data use POST method
            * If post data is empty
            * then use existed data in database 
            */
            function uploadDataV2($file_name = false, $file_data = false)
            {                
                $file_value = $this->uploadImage($file_name);

                if( isset($file_value['error']) && !empty($file_value['error']) )
                {
                    $file_value = $file_data[$file_name];  
                    return $file_value;
                }                                
                return $file_value['upload_data']['file_name'];
            }
			
			/*
            * Upload data V3 use POST method
            * If post data is empty
            * then use existed data in database 
			* @date: 24/11/2012
			 * Use for create news type V3 (upload file in report folder)
			 * INPUT
			 * @file_name: name of input field
			 * @store_folder: 			 
            */
            function uploadDataV3($file_name = false, $store_folder = false, $file_data = false)
            {                
                $file_value = $this->uploadImage2($file_name, $store_folder);

                if( isset($file_value['error']) && !empty($file_value['error']) )
                {
                    $file_value = $file_data[$file_name];
					$this->debug .= $file_value['error'] . "<br/>";  
                    return $file_value;
                }                                
                return $file_value['upload_data']['file_name'];
            }

            /**
             * slug()
             * creates a slug from a string
             */
            function slug($phrase) 
            {
                $find = array('á','à','ả','ã','ạ');
                $phrase = str_replace($find, 'a', $phrase);
				
				$find = array('â','ấ','ầ','ẩ','ẫ','ậ');
                $phrase = str_replace($find, 'a', $phrase);

                $find = array('í','ì','ỉ','ĩ','ị');
                $phrase = str_replace($find, 'i', $phrase);

                $find = array('é','è','ẻ','ẽ','ẹ');
                $phrase = str_replace($find, 'e', $phrase);

                $find = array('ê','ế','ề','ể','ễ','ệ');
                $phrase = str_replace($find, 'e', $phrase);

                $find = array('ý','ỳ','ỷ','ỹ','ỵ');
                $phrase = str_replace($find, 'y', $phrase);

                $find = array('ó','ò','ỏ','õ','ọ');
                $phrase = str_replace($find, 'o', $phrase);     

                $find = array('ô','ố','ồ','ổ','ỗ','ộ');
                $phrase = str_replace($find, 'o', $phrase);     

                $find = array('ơ','ớ','ờ','ở','ỡ','ợ');
                $phrase = str_replace($find, 'o', $phrase);     

                $find = array('ú','ù','ủ','ũ','ụ');
                $phrase = str_replace($find, 'u', $phrase);             

                $find = array('ư','ứ','ừ','ử','ữ','ự');
                $phrase = str_replace($find, 'u', $phrase);  
				
				//adding special case
				//đ
				$find = array('đ');
				$phrase = str_replace($find, 'd', $phrase); 
				           

                $str = strtolower($phrase);

                // replace spaces with underscore, all to lowercase
                $str = strtolower(str_replace(' ', '_', $str));

                // create regex pattern
                $pattern = "/[^a-zA-Z0-9_]/";

                // replace non alphanumeric characters
                $str = preg_replace($pattern, '', $str);

                return $str;
            }

            /*
            * Upload image
            */
            function uploadImage($file_name = false)
            {                

                $config['upload_path'] = './uploads/company/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '10000';
                $config['max_width']  = '2024';
                $config['max_height']  = '1768';                

                $this->load->library('upload', $config);

                $image_field_name = false;
                if( $file_name )
                {
                    $image_field_name = $file_name;
                }
                else
                {
                    $image_field_name = 'image';
                }

                if ( ! $this->upload->do_upload($image_field_name))
                {
                    $error = array('error' => $this->upload->display_errors());
                    $error['file_name'] = $image_field_name;
                    return $error;
                }
                else
                {
                    $data = array('upload_data' => $this->upload->data());
                    return $data;
                }

                return false;
            }

			/*
            * Upload image
			 * @file_name : name of upload field 
			 * @store_folder: folder to store file
            */
            function uploadImage2($file_name = false, $store_folder = false)
            {                

                $config['upload_path'] = './uploads/company/'.$store_folder.'/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size'] = '10000';
                $config['max_width']  = '2024';
                $config['max_height']  = '1768';                

                $this->load->library('upload', $config);

                $image_field_name = false;
                if( $file_name )
                {
                    $image_field_name = $file_name;
                }
                else
                {
                    $image_field_name = 'image';
                }

                if ( ! $this->upload->do_upload($image_field_name))
                {
                    $error = array('error' => $this->upload->display_errors());
                    $error['file_name'] = $image_field_name;
                    return $error;
                }
                else
                {
                    $data = array('upload_data' => $this->upload->data());
                    return $data;
                }

                return false;
            }

            function uploadFile($file_name = false)
            {
               if( isset($_FILES['upload']) )
               {
                    $file = read_file($_FILES['upload']['tmp_name']);
                    $name = basename($_FILES['upload']['name']);
                                        
                    write_file('./uploads/company/report/'.$name, $file);
                                       
                    return $name;                                        
               }
               return false;
            }

            // Function get dowload icon for file
            function getDownloadIcon($file_name = false)
            {
                // get file type
                $pos = strpos($file_name, '.');
                $substr = substr($file_name, $pos);
                $substr = trim($substr);

                if( strstr($substr, 'rar') )
                {
                    return 'rar.jpg';
                }
                elseif( strstr($substr, 'doc') )
                {
                    return 'word-icon.png';
                }
                elseif( strstr($substr, 'docx') )
                {
                    return 'word-icon.png';
                }
                elseif( strstr($substr, 'xls') )
                {
                    return 'excel-icon.png';
                }
                elseif( strstr($substr, 'xlsx') )
                {
                    return 'excel-icon.png';
                }
                else
                {
                    return 'pdf.jpg';
                }
            }
                        
            function showCompanyOptionsBar($company_id = false)
            {
                $current_pathinfo = $_SERVER['PATH_INFO'];                                        

                // company options array
                // link & title
                $company_links = array(
                        'admin/editCompanyInfo/'.$company_id            =>  'Thông tin cơ bản',
                        'admin/editCompanyFinanceInfo/'.$company_id     =>  'Thông tin tài chính',
                        'admin/editCompanyBoard/'.$company_id           =>  'Ban lãnh đạo và sở hữu',
                        'admin/editCompanyAnalyzeBasic/'.$company_id    =>  'Phân tích cơ bản',
                        'admin/editCompanyFinance/'.$company_id         =>  'Bảng giá cổ phiếu',
                        'admin/editCompanyAnalyzeTechnical/'.$company_id         =>  'Phân tích kỹ thuật',
                    );
                $str = '<!--  start step-holder -->
                         <div id="step-holder">
                        ';

                $i = 1;        
                foreach ($company_links as $key => $value) {                    
                    
                    if( strstr(substr($current_pathinfo,1),$key) )
                    {                                                                                                                          
                        $str .= '                       
                            <div class="step-no">'.$i.'</div>
                            <div class="step-dark-left"><a href="'. site_url($key) .'">'.$value.'</a></div>
                            <div class="step-dark-right">&nbsp;</div>                                                    
                        ';                           
                    }
                    else
                    {
                        $str .= '
                            <div class="step-no-off">'.$i.'</div>
                            <div class="step-light-left"><a href="'. site_url($key) .'">'.$value.'</a></div>
                            <div class="step-light-right">&nbsp;</div>

                        ';
                    }
                    
                    $i++;
                }                            

                $str .= '<div class="clear"></div>
                    </div><!--  end step-holder -->';   
                                
                return $str;
            }
            
            function showInvestorOptionsBar()
            {
                $current_pathinfo = $_SERVER['PATH_INFO'];                                        

                // company options array
                // link & title
                $company_links = array(
                        'admin/investor/ndt_trong_nuoc'    =>  'Trong nước',
                        'admin/investor/ndt_nuoc_ngoai'    =>  'Nước ngoài',                        
                    );
                $str = '<!--  start step-holder -->
                         <div id="step-holder">
                        ';

                $i = 1;        
                foreach ($company_links as $key => $value) {                    
                    
                    if( strstr(substr($current_pathinfo,1),$key) )
                    {                                                                                                                          
                        $str .= '                       
                            <div class="step-no">'.$i.'</div>
                            <div class="step-dark-left"><a href="'. site_url($key) .'">'.$value.'</a></div>
                            <div class="step-dark-right">&nbsp;</div>                                                    
                        ';                           
                    }
                    else
                    {
                        $str .= '
                            <div class="step-no-off">'.$i.'</div>
                            <div class="step-light-left"><a href="'. site_url($key) .'">'.$value.'</a></div>
                            <div class="step-light-right">&nbsp;</div>

                        ';
                    }
                    
                    $i++;
                }                            

                $str .= '<div class="clear"></div>
                    </div><!--  end step-holder -->';   
                                
                return $str;
            }

            function showWarning($str = false)
            {
                return '<!--  start message-yellow -->
                <div id="message-yellow">
                <table border="0" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td class="yellow-left">'.$str.'</td>
                    <td class="yellow-right"><a class="close-yellow"><img src="'.base_url('images/table/icon_close_yellow.gif').'"   alt="" /></a></td>
                </tr>
                </table>
                </div>
                <!--  end message-yellow -->';
            }

            function showError($str = false)
            {
                return '<!--  start message-red -->
                <div id="message-red">
                <table border="0" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td class="red-left">'.$str.'</td>
                                        <td class="red-right"><a class="close-red"><img src="'.base_url('images/table/icon_close_red.gif').'"   alt="" /></a></td>
                </tr>
                </table>
                </div>  
                <!--  end message-red -->';
            }

            function showNotify($str = false)
            {
                return '<!--  start message-blue -->
                <div id="message-blue">
                <table border="0" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td class="blue-left">'.$str.'</td>
                    <td class="blue-right"><a class="close-blue"><img src="'. base_url('images/table/icon_close_blue.gif') .'"   alt="" /></a></td>
                </tr>
                </table>
                </div>    
                <!--  end message-blue -->';
            }

            function showSuccess($str = false)
            {
                return '<!--  start message-green -->
                <div id="message-green">
                <table border="0" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td class="green-left">'.$str.'</td>
                    <td class="green-right"><a class="close-green"><img src="'. base_url('images/table/icon_close_green.gif') .'"   alt="" /></a></td>
                </tr>
                </table>
                </div>    
                <!--  end message-green -->';
            }
        }

